package sortTest;

public class InsertDemo {
    public static void main(String[] args) {
        //插入排序
        int[] arr = {3, 22, 46, 4, 37, 13, 33, 7, 9, 35, 8};
        //遍历数组获得无序的开始索引
        int startIndex = -1;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > arr[i + 1]) {
                //这里表明i+1是无序索引的开始
                startIndex = i + 1;
                break;
            }
        }

        for (int i = startIndex; i < arr.length; i++) {
            //在创建变量记录交换值
            int j = i;
            while (j > 0 && arr[j] < arr[j - 1]) {
                int temp = arr[j];
                arr[j] = arr[j - 1];
                arr[j - 1] = temp;
                j--;
            }
        }

        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }

    }
}
